
const express = require('express');
const cors = require('cors');
const multer = require('multer');
const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('uploads'));

// 创建上传目录
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}

// 配置 multer 用于文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadsDir);
  },
  filename: (req, file, cb) => {
    const uniqueName = `${uuidv4()}-${file.originalname}`;
    cb(null, uniqueName);
  }
});

const upload = multer({ 
  storage: storage,
  limits: { fileSize: 10 * 1024 * 1024 }, // 10MB 限制
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['.pdf', '.docx', '.md', '.txt'];
    const ext = path.extname(file.originalname).toLowerCase();
    if (allowedTypes.includes(ext)) {
      cb(null, true);
    } else {
      cb(new Error('不支持的文件类型'), false);
    }
  }
});

// 初始化数据库
const db = new sqlite3.Database('requirements.db');

// 创建表
db.serialize(() => {
  // 项目表
  db.run(`
    CREATE TABLE IF NOT EXISTS projects (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      description TEXT,
      status TEXT DEFAULT 'active',
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  `);

  // 需求表
  db.run(`
    CREATE TABLE IF NOT EXISTS requirements (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project_id INTEGER NOT NULL,
      title TEXT NOT NULL,
      description TEXT,
      priority TEXT DEFAULT 'medium',
      status TEXT DEFAULT 'pending',
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE CASCADE
    )
  `);

  // 文档表
  db.run(`
    CREATE TABLE IF NOT EXISTS documents (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project_id INTEGER NOT NULL,
      requirement_id INTEGER,
      name TEXT NOT NULL,
      original_name TEXT NOT NULL,
      file_path TEXT NOT NULL,
      file_type TEXT NOT NULL,
      file_size INTEGER NOT NULL,
      document_type TEXT NOT NULL, -- 'requirement' 或 'technical'
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE CASCADE,
      FOREIGN KEY (requirement_id) REFERENCES requirements (id) ON DELETE CASCADE
    )
  `);
});

// 项目相关 API
// 获取所有项目
app.get('/api/projects', (req, res) => {
  db.all('SELECT * FROM projects ORDER BY created_at DESC', (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(rows);
  });
});

// 创建项目
app.post('/api/projects', (req, res) => {
  const { name, description } = req.body;
  db.run('INSERT INTO projects (name, description) VALUES (?, ?)', 
    [name, description], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ id: this.lastID, name, description });
  });
});

// 更新项目
app.put('/api/projects/:id', (req, res) => {
  const { name, description, status } = req.body;
  const { id } = req.params;
  
  db.run('UPDATE projects SET name = ?, description = ?, status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
    [name, description, status, id], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ message: '项目更新成功' });
  });
});

// 删除项目
app.delete('/api/projects/:id', (req, res) => {
  const { id } = req.params;
  
  db.run('DELETE FROM projects WHERE id = ?', id, function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ message: '项目删除成功' });
  });
});

// 需求相关 API
// 获取项目的需求
app.get('/api/projects/:projectId/requirements', (req, res) => {
  const { projectId } = req.params;
  
  db.all('SELECT * FROM requirements WHERE project_id = ? ORDER BY created_at DESC', 
    projectId, (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(rows);
  });
});

// 创建需求
app.post('/api/projects/:projectId/requirements', (req, res) => {
  const { projectId } = req.params;
  const { title, description, priority, status } = req.body;
  
  db.run('INSERT INTO requirements (project_id, title, description, priority, status) VALUES (?, ?, ?, ?, ?)',
    [projectId, title, description, priority, status], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ id: this.lastID, project_id: projectId, title, description, priority, status });
  });
});

// 更新需求
app.put('/api/requirements/:id', (req, res) => {
  const { id } = req.params;
  const { title, description, priority, status } = req.body;
  
  db.run('UPDATE requirements SET title = ?, description = ?, priority = ?, status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
    [title, description, priority, status, id], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ message: '需求更新成功' });
  });
});

// 删除需求
app.delete('/api/requirements/:id', (req, res) => {
  const { id } = req.params;
  
  db.run('DELETE FROM requirements WHERE id = ?', id, function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ message: '需求删除成功' });
  });
});

// 文档相关 API
// 上传文档
app.post('/api/projects/:projectId/documents', upload.single('file'), (req, res) => {
  const { projectId } = req.params;
  const { requirementId, documentType } = req.body;
  
  if (!req.file) {
    return res.status(400).json({ error: '没有上传文件' });
  }

  const { originalname, filename, size } = req.file;
  const filePath = `/uploads/${filename}`;
  const fileType = path.extname(originalname).toLowerCase();

  db.run(
    'INSERT INTO documents (project_id, requirement_id, name, original_name, file_path, file_type, file_size, document_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
    [projectId, requirementId || null, filename, originalname, filePath, fileType, size, documentType],
    function(err) {
      if (err) {
        // 如果数据库插入失败，删除已上传的文件
        fs.unlinkSync(path.join(__dirname, filePath));
        res.status(500).json({ error: err.message });
        return;
      }
      res.json({ 
        id: this.lastID, 
        name: filename, 
        original_name: originalname,
        file_path: filePath,
        document_type: documentType 
      });
    }
  );
});

// 获取项目的文档
app.get('/api/projects/:projectId/documents', (req, res) => {
  const { projectId } = req.params;
  
  db.all('SELECT * FROM documents WHERE project_id = ? ORDER BY created_at DESC', 
    projectId, (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(rows);
  });
});

// 下载文档
app.get('/api/documents/:id/download', (req, res) => {
  const { id } = req.params;
  
  db.get('SELECT * FROM documents WHERE id = ?', id, (err, row) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    if (!row) {
      res.status(404).json({ error: '文档不存在' });
      return;
    }
    
    const filePath = path.join(__dirname, row.file_path);
    if (!fs.existsSync(filePath)) {
      res.status(404).json({ error: '文件不存在' });
      return;
    }
    
    res.download(filePath, row.original_name);
  });
});

// 删除文档
app.delete('/api/documents/:id', (req, res) => {
  const { id } = req.params;
  
  db.get('SELECT * FROM documents WHERE id = ?', id, (err, row) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    if (!row) {
      res.status(404).json({ error: '文档不存在' });
      return;
    }
    
    const filePath = path.join(__dirname, row.file_path);
    
    // 删除数据库记录
    db.run('DELETE FROM documents WHERE id = ?', id, function(err) {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }
      
      // 删除物理文件
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
      
      res.json({ message: '文档删除成功' });
    });
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: '服务器内部错误' });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});
